package com.apes.scm.rbac.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.Connector;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.DBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能：岗位增量更新，后期需要修改为JPA版本
 *
 * @author hup
 * @desc 权限相关
 **/
@Service("addPostService")
public class addPostService extends DomainService {
    @Autowired
    Connector connector;

    public JSONObject queryALLMenu(SimpleRequest request) {
        String sql="<rule from=\"C.AUT_MENUS;D.AUT_OPERATIONS\" autoCompletion=\"1\" />\n"+
                "SELECT C.ID AS CDNM, 'ESB-'||C.SORT_CODE AS CDID1, C.NAME AS CDMC, 'ESB' AS XTID,\n" +
                "                REPLACE(WM_CONCAT(D.OPERATION_ID || ':' || D.NAME), ',', ';') ANQXLB\n" +
                "           FROM AUT_MENUS C, AUT_OPERATIONS D\n" +
                "          WHERE C.ID = D.MENU_ID\n" +
                "            AND  (C.LINK LIKE '%/bi/%' OR C.LINK LIKE '%/hr.%' OR C.LINK LIKE '%.customComplain.%')\n" +
                "            AND C.VALID=1 @WHERE@ \n" +
                "   <if test=\"CDID1!=NULL\" >AND 'ESB-'||C.SORT_CODE LIKE '%'||#{CDID1}||'%' </if>\n" +
                "          GROUP BY C.ID, C.NAME, C.SORT_CODE ";
        JSONObject map=new JSONObject();
        try {
            JSONObject json= JSON.toJSON((String)request.getData());
            map.put("rows",getSession().getForJSON().query(sql, json));
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String queryOperMenu(SimpleRequest request) {
        try {
            JSONObject json= JSON.toJSON((String)request.getData());
            String cdnm=json.getString("CDNM");
            String tyjsid=json.getString("TYJSID");
            if(cdnm==null){
                throw new RuntimeException("菜单编码不允许为空!");
            }
            if(tyjsid==null){
                throw new RuntimeException("通用权限编码不允许为空!");
            }
            String sql=" SELECT TO_CHAR(A.KCZGN) KCZGN\n" +
                    "  FROM (SELECT A.ROLE_ID TYJSID, B.NAME AS TYJSMC, A.MENU_ID AS CDNM,\n" +
                    "                REPLACE(WM_CONCAT(A.OPERATION_ID), ',', ';') AS KCZGN\n" +
                    "           FROM AUT_ROLE_OPERATION A, AUT_ROLE B\n" +
                    "          WHERE A.ROLE_ID = B.ID\n" +
                    "          GROUP BY A.ROLE_ID, B.NAME, A.MENU_ID) A,\n" +
                    "       (SELECT C.ID AS CDNM, C.NAME AS CDMC, 'ESB-'||C.SORT_CODE AS CDID,\n" +
                    "                REPLACE(WM_CONCAT(D.OPERATION_ID || ':' || D.NAME), ',', ';') ANQXLB\n" +
                    "           FROM AUT_MENUS C, AUT_OPERATIONS D\n" +
                    "          WHERE C.ID = D.MENU_ID\n" +
                    "            AND  (C.LINK LIKE '%/bi/%' OR C.LINK LIKE '%/hr.%' OR C.LINK LIKE '%.customComplain.%')\n" +
                    "            AND C.VALID=1\n" +
                    "          GROUP BY C.ID, C.NAME, C.SORT_CODE) B\n" +
                    " WHERE A.CDNM = B.CDNM AND A.TYJSID='"+tyjsid+"'\n" +
                    "   AND A.CDNM = '"+cdnm+"'  ";
            JSONArray list=getSession().getForJSON().query(sql);
            if(list.size()==0) return null;
            return ((JSONObject) list.get(0)).getString("KCZGN");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Map updateRole(SimpleRequest request) {
        try {
            JSONObject param= JSON.toJSON((String)request.getData());
            String roleId= param.getString("roleId");
            JSONArray roleOper=JSON.toJSONArray(param.get("roleOperation"));
            int len=roleOper.size();
            for(int i=0; i<len; i++){
                JSONObject p= new JSONObject((Map)roleOper.get(i));
                String add=p.getString("ADD_ANLB");
                String del=p.getString("DEL_ANLB");
                String delMenu=p.getString("DEL_CDNM");
                String menu=p.getString("CDNM");
                String KCZGN=p.getString("KCZGN");
                String hql="";
                if(delMenu!=null && "1".equals(delMenu)){
                    hql="DELETE AUT_ROLE_OPERATION\n" +
                            "WHERE MENU_ID='"+menu+"' AND ROLE_ID IN ("+roleId+")  ";
                    getSession().getForUpdate().update(hql);
                } else {
                    if(KCZGN!=null){
                        hql="DELETE AUT_ROLE_OPERATION   \n" +
                                "WHERE MENU_ID='"+menu+"' AND ROLE_ID IN ("+roleId+") ";
                        getSession().getForUpdate().update(hql);
                        addRole(KCZGN, menu, roleId);
                    }

                    if(add!=null){
                        addRole(add, menu, roleId);
                    }

                    if(del!=null){
                        del=del+";";
                        String[] dellist=del.split(";");
                        int alen=dellist.length;
                        for(int a=0; a<alen; a++){
                            String s=dellist[a];
                            if(s!=""){
                                hql="DELETE AUT_ROLE_OPERATION   \n" +
                                        "WHERE MENU_ID='"+menu+"' AND ROLE_ID IN ("+roleId+") AND OPERATION_ID='"+s+"' ";
                                getSession().getForUpdate().update(hql);
                            }
                        }
                    }
                }

            }
            return new HashMap();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void addRole(String text, String menu, String roleId) throws Exception {
        String str=text;
        str=str+";";
        String hql="";
        String[] addlist=str.split(";");
        int alen=addlist.length;
        for(int a=0; a<alen; a++){
            String s=addlist[a];
            if(s!=""){
                hql="INSERT INTO AUT_ROLE_OPERATION (ROLE_ID, MENU_ID, OPERATION_ID)\n" +
                        "SELECT A.ID,'"+menu+"','"+s+"' FROM AUT_ROLE A \n" +
                        "WHERE A.ID IN ("+roleId+") AND NOT EXISTS (\n" +
                        "  SELECT 1 FROM AUT_ROLE_OPERATION B \n" +
                        "  WHERE B.MENU_ID='"+menu+"' AND A.ID=B.ROLE_ID AND B.ROLE_ID IN ("+roleId+") AND B.OPERATION_ID='"+s+"'\n" +
                        ") ";
                getSession().getForUpdate().update(hql);
            }
        }
    }

    private SqlSession getSession() throws Exception {
        SqlSession session= DBUtil.getSession(getDBName());
        session.setConnection(connector.getConnection());
        return session;
    }

    private String getDBName(){
        return DBUtil.getSysSingleDBName("ESB");
    }

}
